import React, {useState, useEffect} from 'react';
import {Form, Input, Button, Upload, Avatar, message, Space} from 'antd';
import {ArrowLeftOutlined, UploadOutlined, UserOutlined} from '@ant-design/icons';
import './profile-setting.css';
import {useNavigate} from "react-router-dom";
import {fetchUserInfo} from "../../store/modules/userStore";
import {useDispatch} from "react-redux";

const PersonalInfoEditPage = () => {
    const userImg = require("../../assets/images/user_default.png")
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const [avatarUrl, setAvatarUrl] = useState('');
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const [userInfo, setUserInfo] = useState({});

    useEffect(() => {
        dispatch(fetchUserInfo()).then(res => {
            setUserInfo(res.data);
            setForm(res.data);
        }).catch(err => {
            message.error("个人信息获取错误，请尝试重新登录：", err);
        });
    }, []);

    const setForm = (data) => {
        setAvatarUrl(data.avatar);
        form.setFieldsValue({
            username: data.username,
            email: data.email,
            password: data.password
        });
    };

    // 处理表单提交
    const onFinish = (values) => {
        console.log(values);
    };

    // 处理头像上传
    const handleAvatarChange = (info) => {
        console.log("handleAvatarChange info:", info);

        const file = info.file || info.fileList[0];

        if (file.status === 'uploading') {
            setLoading(true);
            console.log('上传中...');
            return;
        }

        const selectedFile = file.originFileObj || file;

        if (selectedFile) {
            const previewUrl = URL.createObjectURL(selectedFile);
            setAvatarUrl(previewUrl);
        } else {
            console.warn("无法获取 originFileObj");
        }

        setLoading(false);
    };


    // 返回主页
    const handleBack = () => {
        navigate('/home');
    };

    // 自定义上传按钮
    const uploadButton = (
        <div>
            <UploadOutlined/>
            <div className="ant-upload-text">上传头像</div>
        </div>
    );

    return (
        <div className="personal-info-container">
            <div className="header">
                <Button
                    type="text"
                    icon={<ArrowLeftOutlined/>}
                    onClick={handleBack}
                    className="back-button"
                />
                <h1>个人信息设置</h1>
                <p>修改你的个人资料和账户设置</p>
            </div>

            <div className="form-wrapper">
                <Form
                    form={form}
                    name="personalInfoForm"
                    onFinish={onFinish}
                    labelCol={{span: 6}}
                    wrapperCol={{span: 14}}
                    scrollToFirstError
                >
                    <Form.Item
                        name="avatar"
                        label="头像"
                        valuePropName="fileList"
                        getValueFromEvent={(e) => {
                            return e?.fileList || [];
                        }}
                    >
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            beforeUpload={() => false} // 禁用自动上传，使用自定义上传逻辑
                            fileList={avatarUrl ? [{url: avatarUrl}] : []}

                            onChange={handleAvatarChange}
                        >
                            {avatarUrl ? (
                                <Avatar
                                    size={120}
                                    src={avatarUrl}
                                    className="preview-avatar"
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        name="username"
                        label="用户名"
                        rules={[
                            {
                                required: true,
                                message: '请输入用户名',
                            },
                            {
                                min: 2,
                                message: '用户名至少包含2个字符',
                            },
                            {
                                max: 20,
                                message: '用户名最多包含20个字符',
                            },
                        ]}
                    >
                        <Input placeholder="请输入用户名"/>
                    </Form.Item>

                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            {
                                type: 'email',
                                message: '请输入有效的邮箱地址',
                            },
                            {
                                required: true,
                                message: '请输入邮箱地址',
                            },
                        ]}
                    >
                        <Input placeholder="请输入邮箱"/>
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[
                            {
                                min: 6,
                                message: '密码至少包含6个字符',
                            },
                            {
                                max: 20,
                                message: '密码最多包含20个字符',
                            },
                        ]}
                        hasFeedback
                    >
                        <Input.Password placeholder="请输入新密码（留空则不修改）"/>
                    </Form.Item>

                    <Form.Item
                        name="confirm"
                        label="确认密码"
                        dependencies={['password']}
                        hasFeedback
                        rules={[
                            {
                                required: false,
                                message: '请确认密码',
                            },
                            ({getFieldValue}) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致!'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password placeholder="请再次输入新密码"/>
                    </Form.Item>

                    <Form.Item wrapperCol={{offset: 6, span: 16}}>
                        <Space size={16}>
                            <Button type="primary" htmlType="submit">
                                保存修改
                            </Button>
                            <Button htmlType="reset">
                                重置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default PersonalInfoEditPage;